<template>
  <div>
    <!--搜索栏-->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.username" placeholder="请输入用户名" clearable />
          <el-input v-model="searchModel.phone" placeholder="请输入手机号" clearable />
          <el-button type="primary" round icon="el-icon-search" @click="getUserList">查询</el-button>
        </el-col>
        <el-col :span="4" align="right">
          <el-button type="primary" icon="el-icon-plus" circle @click="openAddUI(null)" />
        </el-col>
      </el-row>
    </el-card>
    <!--结果，分页-->
    <el-card>
      <template>
        <el-table :data="userList" stripe style="width: 100%">
          <el-table-column prop="id" label="序号" width="180" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column prop="departmentName" label="所属部门" width="180" />
          <el-table-column prop="positionName" label="岗位" width="180" />
          <el-table-column prop="status" label="用户状态" width="180">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮件" />
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="openAddUI(scope.row.id)" />
              <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteUser(scope.row,scope.row.status)" />
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <!--分页组件-->
    <el-card>
      <el-pagination
        :current-page="searchModel.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!--用户信息编辑对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearForm">
      <el-form ref="userForm" :model="userForm" :rules="rules">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="userForm.username" autocomplete="off" />
        </el-form-item>
        <!--        <el-form-item label="密码" prop="password" :label-width="formLabelWidth">-->
        <!--          <el-input v-model="userForm.password" type="password" autocomplete="off">-->
        <!--        </el-form-item>-->
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="userForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属部门" :label-width="formLabelWidth">
          <template>
            <el-select v-model="userForm.departmentId" placeholder="请选择">
              <el-option v-for="(item,index) in departmentList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="所属职位" :label-width="formLabelWidth">
          <template>
            <el-select v-model="userForm.positionId" placeholder="请选择">
              <el-option v-for="(item,index) in positionList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="电子邮件" prop="email" :label-width="formLabelWidth">
          <el-input v-model="userForm.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth">
          <el-switch v-model="userForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-radio-group v-for="role in roleList" v-model="userForm.roleId1">
            <el-radio :key="role.id" :label="role.id">{{ role.roleDesc }}</el-radio>
          </el-radio-group>
          <!--          <el-checkbox-group-->
          <!--            style="width: 85%"-->
          <!--            v-model="userForm.roleIdList"-->
          <!--            :min="1"-->
          <!--            :max="2">-->
          <!--            <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{ role.roleDesc }}-->
          <!--            </el-checkbox>-->
          <!--          </el-checkbox-group>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/userManage'
import roleApi from '@/api/role'

export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'))
      }
      callback()
    }
    return {
      departmentList: [],
      positionList: [],
      roleList: [],
      formLabelWidth: '130px',
      userForm: {
        roleId1: {}
      },
      dialogFormVisible: false,
      title: '',
      total: 0,
      searchModel: {
        page: 1,
        pageSize: 10
      },
      userList: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
    this.getAllRoleList()
  },
  methods: {
    getAllRoleList() {
      roleApi.getAllRoleList().then(res => {
        this.roleList = res.data
      })
    },
    deleteUser(user, status) {
      if (status === 1) {
        this.$message({
          type: 'error',
          message: '该数据正在使用，无法删除'
        })
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          userApi.deleteUser(user.id).then(res => {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.getUserList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    saveUser() {
      // 触发表单验证
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          // 提交请求给后台
          userApi.saveUser(this.userForm).then(res => {
            // 成功提示，关闭对话框，刷新数据
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.dialogFormVisible = false
            this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearForm() {
      this.userForm = {
        roleIdList: []
      }
      this.$refs.userForm.clearValidate()
    },
    openAddUI(id) {
      this.dialogFormVisible = true
      userApi.getDepartmentName({ 'status': 1 }).then(res => {
        this.departmentList = res.data
      })
      userApi.getPositionName({ 'status': 1 }).then(res => {
        this.positionList = res.data
      })

      if (id == null) {
        this.title = '新增用户'
      } else {
        this.title = '修改用户'
        userApi.getUserById(id).then(res => {
          this.userForm = res.data
        })
      }
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(page) {
      this.searchModel.page = page
      this.getUserList()
    },
    getUserList() {
      userApi.getUserList(this.searchModel).then(res => {
        this.userList = res.data.rows
        this.total = res.data.total
      })
    }
  }
}
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}

.el-dialog .el-input {
  width: 85%;
}
</style>
